﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;
using WorkFlowCore.Authorization;
using WorkFlowCore.FormDesigns;
using WorkFlowCore.Framework.MultipleApp;
using WorkFlowCore.IRepositories;
using WorkFlowCore.Workflows;

namespace WorkFlowCore.Framework.Repositories4EF
{
    internal class FormDesignInfoRepository : BasicRepository<FormDesignInfo, Guid>, IFormDesignInfoRepository
    {
        public FormDesignInfoRepository(IWorkflowSession session, IDbContextProvider<WorkflowDbContext> dbContextProvider) : base(session, dbContextProvider)
        {
            Session = session;
            DbContextProvider = dbContextProvider;
        }

        public IWorkflowSession Session { get; }
        public IDbContextProvider<WorkflowDbContext> DbContextProvider { get; }

        public async Task<List<FormDesign>> GetFormDesignsOfWorkflowId(WorkflowId4FormDesign[] workflowIds)
        {
            var workflow_Ids = workflowIds.Select(id => id.Id).ToArray();
            var workflow_Nos = workflowIds.Select(id => id.Version).ToArray();

            var formDesignVersionQuery = DbContextProvider.GetDbContext().Set<FormDesignVersion>()
                .AsNoTracking().WhereMultipleApp(Session?.User?.AppId)
                .Where(v=>v.Deleted == false);

            var formDesignQuery = DbContextProvider.GetDbContext().Set<FormDesignInfo>()
                .AsNoTracking().WhereMultipleApp(Session?.User?.AppId)
                .Where(f => f.Deleted == false && workflow_Ids.Contains(f.WorkflowId_Id) && workflow_Nos.Contains(f.WorkflowId_Version))
                .Where(f => formDesignVersionQuery.Any(v => v.FormDesignId == f.Id && v.Version == f.ActiveVersion))
                ;
            return formDesignQuery.Select(f=>f).Select(f => f.ToFormDesign()).ToList();
        }
    }
}
